package com.mate.cloud.xml.bean;

import com.mate.cloud.xml.AbstractTestCase;
import com.mate.cloud.xml.domain.Student;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.bean.BeanDocumentFactory;
import org.dom4j.io.SAXReader;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.util.Assert;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;


/**
 * DOCUMENT ME!
 * <a href="mailto:maartenc@users.sourceforge.net">Maarten Coene </a>
 *
 * @author: MI
 * @email: 448341911@qq.com
 * @createTime: 2024/6/2 19:22
 * @updateUser: MI
 * @updateTime: 2024/6/2 19:22
 * @updateRemark: 修改内容
 * @version: v1.0
 */
@Slf4j
@SpringBootTest
public class BeanTests extends AbstractTestCase {

    @Test
    public void testReadXML() throws Exception {
        ResourceLoader resourceLoader = new DefaultResourceLoader();
        Resource resource = resourceLoader.getResource("classpath:xml/bean/gui.xml");
        Assert.isTrue(resource.exists(), "XML file not found");
        // 1、创建SAXReader
        SAXReader saxReader = SAXReader.createDefault();
        // 2、将xml解析为树
        Document document = getDocument(resource.getInputStream(), saxReader);
        // 3、获得根节点
        Element rootElement = document.getRootElement();
        // 4、输出根元素名称（示例）
        System.out.println(rootElement.getName());
    }

    /**
     * 使用dom4j读xml
     * @throws Exception
     */
    @Test
    public void testReadStudentsXML() throws Exception {
        ResourceLoader resourceLoader = new DefaultResourceLoader();
        Resource resource = resourceLoader.getResource("classpath:xml/bean/students.xml");

        Assert.isTrue(resource.exists(), "XML file not found");
        // 1、创建SAXReader
        SAXReader saxReader = SAXReader.createDefault();
        // 2、将xml解析为树
        Document document = getDocument(resource.getInputStream(), saxReader);
        // 3、获得根节点
        Element rootElement = document.getRootElement();
        // 4、获取所有student节点并映射成学生对象(这里假设我不知道student节点在哪一级，或者哪几级)
        List<Student> students = mapElementsToStudents(rootElement.elements());

        students.forEach(student -> log.info(MessageFormat.format("\t Student#name=:{0},\t Student#age=:{1}\t Student#location=:{2}", student.getName(), student.getAge(), student.getLocation())));
    }

    private static List<Student> mapElementsToStudents(List<Element> elements) {
        List<Student> students = new ArrayList<>();
        elements.stream().forEach(element -> {
            // 转换当前节点
            if ("student".equals(element.getName())) {
                Optional.ofNullable(mapElementToStudent(element)).ifPresent(students::add);
            }
            // 递归转换子节点
            students.addAll(mapElementsToStudents(element.elements()));
        });
        return students;
    }

    private static Student mapElementToStudent(Element element) {
        Student student = new Student();
        Optional.ofNullable(element.attributeValue("name")).ifPresent(student::setName);
        Optional.ofNullable(element.attributeValue("age")).map(Integer::valueOf).ifPresent(student::setAge);
        Optional.ofNullable(element.attributeValue("location")).ifPresent(student::setLocation);
        return student;
    }

}
